﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace FDStudio.Core.Repositories
{
    /*
     CreatedOn: 2018-07-12
     CreatedBy: Jackie Lee(天宇遊龍)
     */
    /// <summary>
    /// 抽象仓储上下文基类
    /// </summary>
    public abstract class BaseContext
    {
        /// <summary>
        /// 事务相关连接
        /// </summary>
        protected IDbConnection _dbConnection;
        protected IDbTransaction _dbTransaction;
        private int _transactionCount;

        /// <summary>
        /// 创建数据库连接
        /// </summary>
        /// <returns></returns>
        public abstract IDbConnection CreateConnection();

        /// <summary>
        /// 是否事务状态
        /// </summary>
        protected bool IsTranscation => _transactionCount > 0;

        /// <summary>
        /// 开启事务
        /// </summary>
        public virtual void BeginTransaction()
        {
            _transactionCount++;
            if (_transactionCount == 1)
            {
                _dbConnection = CreateConnection();
                _dbConnection.Open();
                _dbTransaction = _dbConnection.BeginTransaction();
            }
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        public virtual void CommitTransaction()
        {
            _transactionCount--;
            if (_transactionCount == 0)
            {
                _dbTransaction.Commit();
                DisposeTransaction();
            }
        }

        /// <summary>
        /// 回滚事务
        /// </summary>
        public virtual void RollbackTransaction()
        {
            _transactionCount--;
            _dbTransaction.Rollback();
            DisposeTransaction();
        }

        /// <summary>
        /// 释放事务
        /// </summary>
        /// <param name="bForece"></param>
        protected void DisposeTransaction(bool bForece = false)
        {
            if (_transactionCount == 0 || bForece)
            {
                if (_dbTransaction != null)
                    _dbTransaction.Dispose();
                if (_dbConnection != null)
                {
                    _dbConnection.Close();
                    _dbConnection.Dispose();
                }
                _dbTransaction = null;
                _dbConnection = null;
            }
        }
    }
}
